﻿namespace Sharemarker.DataAccess.Mysql
{
    using System;

    using MySql.Data.MySqlClient;

    using log4net;

    /// <summary>
    /// 
    /// </summary>
    public class SharemarkerAccountRepository : ISharemarkerAccountRepository
    {
        #region Static Fields

        /// <summary>
        /// 
        /// </summary>
        private static readonly ILog Logger = LogManager.GetLogger(typeof(SharemarkerAccountRepository));

        #endregion

        #region Fields

        /// <summary>
        /// 
        /// </summary>
        private readonly string connectionString;

        #endregion

        #region Constructors and Destructors

        /// <summary>
        /// Initializes a new instance of the <see cref="SharemarkerAccountRepository" /> class.
        /// </summary>
        /// <param name="connectionString">The connection string.</param>
        public SharemarkerAccountRepository(string connectionString)
        {
            this.connectionString = connectionString;
        }

        #endregion

        #region Public Methods and Operators

        /// <summary>
        /// Determines whether [is existed account] [the specified username].
        /// </summary>
        /// <param name="username">The username.</param>
        /// <param name="password">The password.</param>
        /// <returns>
        ///   <c>true</c> if [is existed account] [the specified username]; otherwise, <c>false</c>.
        /// </returns>
        /// <exception cref="System.NotImplementedException"></exception>
        public bool DoesAccountExistedInSystem(string username, string password)
        {
            int resultCount = 0;

            using (var conn = new MySqlConnection(this.connectionString))
            {
                conn.Open();
                try
                {
                    var cmd =
                        new MySqlCommand(
                            string.Format(
                                "SELECT COUNT(*) FROM Account WHERE Username = '{0}' And Password = '{1}'",
                                username,
                                password),
                            conn);
                    object result = cmd.ExecuteScalar();
                    if (result != null)
                    {
                        resultCount = Convert.ToInt32(result);
                    }
                }
                catch (Exception ex)
                {
                    // TODO: apply log4net 
                }

                conn.Close();
            }

            return resultCount > 0;
        }

        #endregion
    }
}